package com.adam.masterSpringMVC4.controller;

import com.adam.masterSpringMVC4.weibo.AsyncSearch;
import com.adam.masterSpringMVC4.weibo.ParallelSearchService;
import com.adam.masterSpringMVC4.weibo.WeiboData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Controller
public class SearchWebSocketController {
//    @Autowired
//    private ParallelSearchService parallelSearchService;
    @Autowired
    private AsyncSearch asyncSearch;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/search")
    public void search(@Payload List<String> keywords) {
//        String channel = "/topic/searchResults/" + StringUtils.collectionToDelimitedString(keywords, ",");
//        List<WeiboData> weiboDataList = parallelSearchService.search("mixed", keywords);
        keywords.stream()
                .forEach(keyword -> {
                    asyncSearch.asyncFetch("mixed", keyword)
                            .addCallback(weiboDataList -> messagingTemplate.convertAndSend("/topic/searchResults/" + keyword, wrapMessage(weiboDataList, keyword)),
                                    Throwable::printStackTrace);
                });
    }

    private Map<String, Object> wrapMessage(List<WeiboData> weiboDataList, String keyword) {
        Map<String, Object> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("data", weiboDataList);
        return map;
    }
}
